package com.example.tms.realtime.utils;

import com.example.tms.realtime.common.TmsConfig;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * ClassName: HbaseUtil
 * Package: com.example.tms.realtime.utils
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-08-01
 * Time: 20:33
 */

//操作HBase的工具类
public class HbaseUtil {
    //创建连接 单例的
    private static Connection conn;

    //创建一个饿汉式的单例模式
    static {
        try {
            Configuration conf = HBaseConfiguration.create();
            //想连接到hbase 要先连接到zookeeper
            conf.set("hbase.zookeeper.quorum", TmsConfig.HBASE_ZOOKEEPER_QUORUM);
            conn = ConnectionFactory.createConnection(conf);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //创建表 参数分别为 库名 表明 列族 每种数据库(可变参数) 叫法不一样
    public static void createTable(String nameSpace, String tableName, String... families) {

        //获取admin对象
        Admin admin = null;
        try {
            //列族是一定要有的 如果为空 给一个默认值
            if (families.length < 1) {
                //可变参数底层是一个数组
                System.out.println("至少要一个列族");
                return;
            }

            admin = conn.getAdmin();
            //创建表 程序肯能被启动多次 第二次启动就不必在创建
            //创建之前 判断 表是否存在
            if (admin.tableExists(TableName.valueOf(nameSpace, tableName))) {
                System.out.println(nameSpace + ":" + tableName + "已存在");
                return;
            }

            TableDescriptorBuilder builder = TableDescriptorBuilder.newBuilder(TableName.valueOf(nameSpace, tableName));
            //指定列族
            for (String family : families) {
                ColumnFamilyDescriptor fam = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(family)).build();
                builder.setColumnFamily(fam);

            }
            admin.createTable(builder.build());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (admin != null){
                try {
                    admin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}